using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Outlook;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using OutlookPanel;
using TeamXpandLicence.ObjectExchange;
using TXLooker.Common;
using TXLooker.Common.Core;
using TXLooker.Common.EventHandling;
using TXLooker.Common.Extentions;
using TXLooker.Common.FileFormatCoverters;
using TXLooker.Common.Outlook;
using TXLooker.Common.UI;
using TXLooker.WorkItemExtention.Core;
using TXLooker.WorkItemExtention.Properties;
using TXLooker.WorkItemExtention.UI;
using TXLooker.WorkItemExtention.UI.OLViewExtension;
using TXLooker.WorkItemExtention.WIQL;
using Application = Microsoft.Office.Interop.Outlook.Application;
using Exception = System.Exception;
using MAPIFolder = Microsoft.Office.Interop.Outlook.MAPIFolder;
using Timer = System.Threading.Timer;
using Microsoft.TeamFoundation.WorkItemTracking.Controls;


namespace TXLooker.WorkItemExtention
{
    public class ExtentionEntryPoint : IExtentionEntryPoint, IOlProjectProcessor
    {
        
        #region Fields
        private const int AddToFavoriteFolderButtonId = 0x1ed0;
        private const int CopyButtonId = 0x9c3;
        private const int DeleteButtonId = 0x9c4;
        private static Application m_App;
        private EventHandler m_ApplicationConfigsChangedEH = null;
        private bool m_bStandartInspector = false;
        private int m_comboReassignToItemsCount = 0;
        private WorkItemAppConfigs m_configs = null;
        protected IExtentionDataProvider m_DataProvider = null;
        private List<Explorer> m_explorers = new List<Explorer>();
        private Inspectors m_inspectors = null;
        private ItemEvents_10_Event m_item = null;
        private List<string> m_loadedFolders = new List<string>();
        private List<IServerProvider> m_servers = new List<IServerProvider>();
        private List<StateButton> m_stateChangeButtons = new List<StateButton>();
        private object m_syncApplicationConfigs = new object();
        private object m_syncWebViewsMAP = null;
        private Dictionary<UIControlType, List<CommandBarControl>> m_UIControls = new Dictionary<UIControlType, List<CommandBarControl>>();
        private Timer m_updateTimer;
        private Dictionary<WebViewType, string> m_webViewsMAP = null;
        private const int MarkAllAsRead = 0x2730;
        private const int MoveButtonId = 0x9ca;
        private const int NewFolderButtonId = 0x67c;
        private const int PropertiesButtonId = 750;
        private const int RenameButtonId = 0x9d0;
        protected CommandBar TeamXpandCommandBar = null;
        private Common.EventHandling.EventSink eventSink;
        private IntPtr siblingWindow;
        private IntPtr outlookWindow;


        private const string SIBLING_WINDOW_CLASS = "rctrl_renwnd32";
        private const string OUTLOOK_PROCESS_NAME = "outlook";
        private PanelManager panelManager;
        private OLQueryViewControl olQueryViewControl;
        private OLServerViewControl OLServerViewControl;
        private System.Windows.Forms.Timer refreshTimer; 
        #endregion

        #region Properties
        private Explorer ActiveExplorer
        {
            get
            {
                return m_App.ActiveExplorer();
            }
        }

        public static Application Application
        {
            get
            {
                return m_App;
            }
        }

        protected WorkItemAppConfigs ApplicationConfigs
        {
            get
            {
                return this.m_configs;
            }
        }

        public string Name
        {
            get
            {
                return Resources.EXTENTION_NAME;
            }
        }

        public IEnumerable<IServerProvider> Servers
        {
            get
            {
                return this.m_servers;
            }
        }

        #endregion

        #region Events

        public event EventHandler ApplicationConfigsChanged
        {
            add
            {
                lock (this.m_syncApplicationConfigs)
                {
                    this.m_ApplicationConfigsChangedEH = (EventHandler)Delegate.Combine(this.m_ApplicationConfigsChangedEH, value);
                }
            }
            remove
            {
                lock (this.m_syncApplicationConfigs)
                {
                    this.m_ApplicationConfigsChangedEH = (EventHandler)Delegate.Remove(this.m_ApplicationConfigsChangedEH, value);
                }
            }
        } 

        #endregion

        #region Methods

        private void AddWorkItem(WorkItem wiItem)
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                new WorkItemForm(wiItem, this).Show();
            }
        }

        private void AsyncUpdateData(MAPIFolder folder)
        {
            if (this.CheckFolder(folder))
            {
                WaitCallback callBack = delegate(object state)
                {
                    this.UpdateData(folder);
                };
                ThreadPool.QueueUserWorkItem(callBack);
            }
        }

        private bool btnContentPatternOption_Click()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                new WorkItemTypePatternEditorForm().ShowDialog();
                foreach (IServerProvider provider in this.Servers)
                {
                    this.SaveWIProjectSettings(WIAppGlobal.Configs.GetProjectSettingsList(provider.Server.Uri), provider.Server.Uri);
                }
                this.RaiseApplicationConfigsChanged();
            }

            return false;
        }

        private bool btnUpdateOption_Click()
        {
            WorkItemAppConfigs settings = this.ApplicationConfigs.Clone() as WorkItemAppConfigs;
            WorkItemUpdateForm form = new WorkItemUpdateForm(settings);
            if (form.ShowDialog() == DialogResult.OK)
            {
                this.ApplicationConfigs.SetDataFrom(form.WorkItemAppConfigs);
                this.SaveConfigs(this.ApplicationConfigs);
                this.RaiseApplicationConfigsChanged();
            }

            return false;
        }

        public void ChangeWorkItemsState(string state)
        {
            try
            {
                var activeExplorer = ActiveExplorer;

                var objectByFolder = WIObject.GetObjectByFolder(activeExplorer.CurrentFolder);
                if ((objectByFolder != null) && (objectByFolder.Type == WIObjectType.Query))
                {
                    var wi = GetSelectedWorkItem();
                    if (wi != null)
                    {
                        wi.Fields[CoreField.State].Value = state;
                        var inValidFields = wi.Validate();
                        var InValidFields = String.Empty;
                        if (inValidFields.Count != 0)
                        {
                            var MessagePattern = "Field(s) \n\n {0} \n are filled incorrect. Please correct.";
                            foreach (Field field in inValidFields)
                            {
                                InValidFields += String.Format("'{0}'\n", field.Name);
                            }

                            var message = String.Format(MessagePattern, InValidFields);

                            MessageBox.Show(message, "TXLooker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        wi.Save();
                        if (olQueryViewControl != null)
                            ActiveExplorer_FolderSwitch();
                    }

                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private bool CheckFolder(MAPIFolder folder)
        {
            if (folder == null)
            {
                return false;
            }
            if (folder.StoreID != this.m_DataProvider.AppStoreID)
            {
                return false;
            }
            foreach (MAPIFolder folder2 in this.m_DataProvider.OlStandardFolders)
            {
                if (folder.EntryID == folder2.EntryID)
                {
                    return false;
                }
            }
            return true;
        }

        private void CreateAppCommandBar()
        {
            CommandBars commandBars = this.ActiveExplorer.CommandBars;
            bool lookerCommandBarIsCreated = false;
            foreach (CommandBar bar in commandBars)
            {
                if (bar.Name == this.Name)
                {
                    lookerCommandBarIsCreated = true;
                    this.TeamXpandCommandBar = bar;
                    break;
                }
            }
            if (!lookerCommandBarIsCreated)
            {
                TeamXpandCommandBar = CreateCommandBar(commandBars, Name);
                InitButtons(TeamXpandCommandBar);
            }

            TeamXpandCommandBar.Visible = true;
        }

        private CommandBar CreateCommandBar(CommandBars bars, string caption)
        {
            return bars.Add(caption, MsoBarPosition.msoBarTop, Missing.Value, true);
        }

        private void CreateAppUIControls()
        {
            this.CreateAppCommandBar();
            this.UpdateMainMenuBar();
            MAPIFolder currentFolder = this.ActiveExplorer.CurrentFolder;
            bool bEnabled = this.CheckFolder(currentFolder);
            this.EnabledControls(bEnabled);
            if (bEnabled)
            {
                this.UpdateStateControls(this.ApplicationConfigs);
            }
        }

        private string CreateBody(WorkItem item, TextFormatType targetType)
        {
            string sourceString = string.Empty;
            ContentPattern pattern;
            WIProjectProvider projectProvider = WIObjectsStore.GetServer(item.Store.TeamFoundationServer.Uri).GetProjectProvider(item.Project.Uri);
            if (projectProvider == null)
            {
                //throw new Exception();
                pattern = new ContentPattern
                {
                    Format = TextFormatType.Html,
                    Pattern = Resources.DEFAULT_HTML_CONTENT_PATTERN
                };
            }
            else
                pattern = projectProvider.Settings[item.Type.Name];
            if (pattern == null)
            {
                return sourceString;
            }
            sourceString = pattern.Pattern;
            foreach (Field field in item.Fields)
            {
                object obj2 = item[field.Name];
                string newValue = (obj2 == null) ? string.Empty : obj2.ToString();
                sourceString = sourceString.Replace(string.Format(Resources.FIELD_CONTENT_PATTERN, field.Name.Replace(" ", string.Empty)), newValue);
            }
            return OlFormatConverter.ConvertHtmlTo(this.m_DataProvider.AppMAPIFolderRoot.Application, sourceString, targetType);
        }

        private void CreateOlInspectorByFolder(MAPIFolder folder, OlItemType type)
        {
            WIObject objectByFolder = WIObject.GetObjectByFolder(folder);
            if (objectByFolder != null)
            {
                switch (objectByFolder.Type)
                {
                    case WIObjectType.Server:
                        switch (type)
                        {
                            case OlItemType.olMailItem:
                                this.CreateSimpleOlEmail();
                                return;

                            case OlItemType.olAppointmentItem:
                                this.CreateSimpleOlMeeting();
                                return;

                            case OlItemType.olContactItem:
                                goto Label_00BC;

                            case OlItemType.olTaskItem:
                                this.CreateSimpleOlTask();
                                return;
                        }
                        goto Label_00BC;

                    case WIObjectType.Project:
                    case WIObjectType.QueriesRoot:
                    case WIObjectType.QueriesGroup:
                        {
                            WIProjectProvider provider = (objectByFolder.Type == WIObjectType.Project) ? ((WIProjectProvider)objectByFolder) : ((WIProjectProvider)objectByFolder.GetType().InvokeMember("ProjectProvider", BindingFlags.GetProperty, null, objectByFolder, null));
                            Project project = null;
                            try
                            {
                                project = provider.GetProject();
                            }
                            catch
                            {
                            }
                            if (project == null)
                            {
                                MessageBox.Show(Resources.SERVER_ACCESS_ERROR_MESSAGE, Resources.EXTENTION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                return;
                            }
                            switch (type)
                            {
                                case OlItemType.olMailItem:
                                    this.CreateOlProjectEmail(project);
                                    return;

                                case OlItemType.olAppointmentItem:
                                    this.CreateOlProjectMeeting(project);
                                    return;

                                case OlItemType.olContactItem:
                                    goto Label_0166;

                                case OlItemType.olTaskItem:
                                    this.CreateOlProjectTask(project);
                                    return;
                            }
                            goto Label_0166;
                        }
                    case WIObjectType.Query:
                        {
                            var wi = GetSelectedWorkItem();

                            if (object.ReferenceEquals(wi, null))
                            {
                                MessageBox.Show(Resources.WORKITEM_ERROR_RECEIVE_MESSAGE, Resources.EXTENTION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                return;
                            }
                            switch (type)
                            {
                                case OlItemType.olMailItem:
                                    this.CreateOlWorkItemEmail(wi);
                                    return;

                                case OlItemType.olAppointmentItem:
                                    this.CreateOlWorkItemMeeting(wi);
                                    return;

                                case OlItemType.olContactItem:
                                    goto Label_0213;

                                case OlItemType.olTaskItem:
                                    this.CreateOlWorkItemTask(wi);
                                    return;
                            }
                            goto Label_0213;
                        }
                }
                throw new NotImplementedException();
            }
            switch (type)
            {
                case OlItemType.olMailItem:
                    this.CreateSimpleOlEmail();
                    return;

                case OlItemType.olAppointmentItem:
                    this.CreateSimpleOlMeeting();
                    return;

                case OlItemType.olTaskItem:
                    this.CreateSimpleOlTask();
                    return;

                default:
                    throw new NotImplementedException();
            }
        Label_00BC:
            throw new NotImplementedException();
        Label_0166:
            throw new NotImplementedException();
        Label_0213:
            throw new NotImplementedException();
        }

        public void CreateOlProjectEmail(Project project)
        {
            this.m_bStandartInspector = true;
            MailItem olMail = (MailItem)this.m_DataProvider.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olMailItem);
            this.CreateProjectMailContent(ref olMail, project);
            olMail.Display(false);
            this.m_bStandartInspector = false;
        }

        public void CreateOlProjectMeeting(Project project)
        {
            this.m_bStandartInspector = true;
            AppointmentItem item = (AppointmentItem)this.m_DataProvider.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items.Add(OlItemType.olAppointmentItem);
            this.CreateProjectMeetingContent(ref item, project);
            item.Display(false);
            this.m_bStandartInspector = false;
        }

        public void CreateOlProjectTask(Project project)
        {
            this.m_bStandartInspector = true;
            TaskItem item = (TaskItem)this.m_DataProvider.Session.GetDefaultFolder(OlDefaultFolders.olFolderTasks).Items.Add(OlItemType.olTaskItem);
            this.CreateProjectTaskContent(ref item, project);
            item.Display(false);
            this.m_bStandartInspector = false;
        }

        public void CreateOlWorkItemEmail(WorkItem workItem)
        {
            MailItem item = (MailItem)this.m_DataProvider.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olMailItem);
            this.CreateOlWorkItemEmail(workItem, item);
        }

        public void CreateOlWorkItemEmail(WorkItem workItem, MailItem item)
        {
            this.m_bStandartInspector = true;
            this.CreateWorkItemMailContent(ref item, workItem);
            try
            {
                item.Display(false);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.ToString());
                Debug.Assert(false, exception.ToString());
            }
            this.m_bStandartInspector = false;
        }

        public void CreateOlWorkItemMeeting(WorkItem workItem)
        {
            AppointmentItem item = (AppointmentItem)this.m_DataProvider.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items.Add(OlItemType.olAppointmentItem);
            this.CreateOlWorkItemMeeting(workItem, item);
        }

        public void CreateOlWorkItemMeeting(WorkItem workItem, AppointmentItem item)
        {
            this.m_bStandartInspector = true;
            this.CreateWorkItemMeetingContent(ref item, workItem);
            try
            {
                item.Display(false);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
            this.m_bStandartInspector = false;
        }

        public void CreateOlWorkItemTask(WorkItem workItem)
        {
            TaskItem item = (TaskItem)this.m_DataProvider.Session.GetDefaultFolder(OlDefaultFolders.olFolderTasks).Items.Add(OlItemType.olTaskItem);
            this.CreateOlWorkItemTask(workItem, item);
        }

        public void CreateOlWorkItemTask(WorkItem workItem, TaskItem item)
        {
            this.m_bStandartInspector = true;
            this.CreateWorkItemTaskContent(ref item, workItem);
            try
            {
                item.Display(false);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.ToString());
                Debug.Assert(false, exception.ToString());
            }
            this.m_bStandartInspector = false;
        }

        private void CreateProjectMailContent(ref MailItem olMail, Project project)
        {
            MailItem item = (MailItem)m_App.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olMailItem);
            olMail.Subject = this.GenerateProjectSubject(project);
            switch (item.BodyFormat)
            {
                case OlBodyFormat.olFormatPlain:
                    olMail.Body = this.GenerateProjectPlainBody(project);
                    break;

                case OlBodyFormat.olFormatHTML:
                    olMail.HTMLBody = this.GenerateProjectHtmlBody(project);
                    break;

                case OlBodyFormat.olFormatRichText:
                    // !Attention. Now Outlook 2007 API doesn't contain a direct way to set RTF Body
                    //olMail.RtfBody = this.GenerateProjectRtfBody(project);
                    olMail.Body = this.GenerateProjectRtfBody(project);
                    break;
            }
        }

        private void CreateProjectMeetingContent(ref AppointmentItem item, Project project)
        {
            if (!object.ReferenceEquals(project, null))
            {
                item.Subject = this.GenerateProjectSubject(project);
            }
        }

        private void CreateProjectTaskContent(ref TaskItem item, Project project)
        {
            if (!object.ReferenceEquals(project, null))
            {
                item.Subject = this.GenerateProjectSubject(project);
            }
        }

        private void CreateReassigneToComboBox(CommandBar parent)
        {
            RegisterUIControl(
                UIControlType.ReassignTo,

                uiFactory.CreateComboBox(parent, Resources.STRING_REASSIGN_TO_DESCRIPTION,
                                         Resources.STRING_REASSIGN_TO_DESCRIPTION, Resources.UI_REASSIGN_TO_TOOL_TIP, 150,
                                         10, OnReassignToChange)

            );
        }

        private void CreateSimpleOlEmail()
        {
            this.m_bStandartInspector = true;
            ((MailItem)m_App.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olMailItem)).Display(false);
            this.m_bStandartInspector = false;
        }

        private void CreateSimpleOlMeeting()
        {
            this.m_bStandartInspector = true;
            ((AppointmentItem)m_App.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items.Add(OlItemType.olAppointmentItem)).Display(false);
            this.m_bStandartInspector = false;
        }

        private void CreateSimpleOlTask()
        {
            this.m_bStandartInspector = true;
            ((TaskItem)m_App.Session.GetDefaultFolder(OlDefaultFolders.olFolderTasks).Items.Add(OlItemType.olTaskItem)).Display(false);
            this.m_bStandartInspector = false;
        }

        private void CreateWorkItemMailContent(ref MailItem olMail, WorkItem workItem)
        {
            MailItem item = (MailItem)m_App.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olMailItem);
            olMail.Subject = this.GenerateWorkItemSubject(workItem);
            switch (item.BodyFormat)
            {
                case OlBodyFormat.olFormatPlain:
                    olMail.Body = this.GenerateWorkItemPlainBody(workItem);
                    break;

                case OlBodyFormat.olFormatHTML:
                    olMail.HTMLBody = this.GenerateWorkItemHtmlBody(workItem);
                    break;

                case OlBodyFormat.olFormatRichText:
                    // !Attention. Now Outlook 2007 API doesn't contain a direct way to set RTF Body
                    //olMail.RTFBody = this.GenerateWorkItemRtfBody(workItem);
                    olMail.HTMLBody = this.GenerateWorkItemHtmlBody(workItem);
                    break;
            }
        }

        private void CreateWorkItemMeetingContent(ref AppointmentItem olAppointment, WorkItem workItem)
        {
            olAppointment.Subject = this.GenerateWorkItemSubject(workItem);
            // !Attention. Now Outlook 2007 API doesn't contain a direct way to set RTF Body
            //olAppointment.RTFBody = this.GenerateWorkItemRtfBody(workItem);
            olAppointment.Body = this.GenerateWorkItemPlainBody(workItem);
        }

        private void CreateWorkItemTaskContent(ref TaskItem item, WorkItem workItem)
        {
            TaskItem item2 = (TaskItem)m_App.Session.GetDefaultFolder(OlDefaultFolders.olFolderOutbox).Items.Add(OlItemType.olTaskItem);
            item.Subject = this.GenerateWorkItemSubject(workItem);
            // !Attention. Now Outlook 2007 API doesn't contain a direct way to set RTF Body
            //item.RTFBody = this.GenerateWorkItemRtfBody(workItem);
            item.Body = this.GenerateWorkItemPlainBody(workItem);
        }

        private void EditWorkItem(PostItem olItem)
        {
            WorkItem workItemByOlItem = this.GetWorkItemByOlItem(olItem);
            if (workItemByOlItem == null)
            {
                MessageBox.Show(Resources.WORKITEM_ERROR_RECEIVE_MESSAGE, Resources.EXTENTION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            else
            {
                this.EditWorkItem(workItemByOlItem, olItem);
            }
        }

        private void EditWorkItem(WorkItem wiItem, PostItem olItem)
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                new WorkItemForm(wiItem, olItem, this).Show();
            }
        }

        private void EnabledControls(bool bEnabled)
        {
            this.EnabledControls((UIControlType[])Enum.GetValues(typeof(UIControlType)), bEnabled);
            if (!bEnabled)
            {
                this.EnabledControls(UIControlType.Options, true);
                this.EnabledControls(UIControlType.WorkItem, true);
                this.EnabledControls(UIControlType.NewWorkItem, true);
            }
        }

        private void EnabledControls(UIControlType[] ctrlTypes, bool bEnabled)
        {
            foreach (UIControlType type in ctrlTypes)
            {
                try
                {
                    this.EnabledControls(type, bEnabled);
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog("Error in EnabledControls " + exception.ToString());
                }
            }
        }

        private void EnabledControls(UIControlType ctrlType, bool bEnabled)
        {
            foreach (CommandBarControl control in this.m_UIControls[ctrlType])
            {
                try
                {
                    control.Enabled = bEnabled;
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog("Error EnabledControls " + exception.ToString());
                }
            }
        }

        private string GenerateProjectHtmlBody(Project project)
        {
            return string.Empty;
        }

        private string GenerateProjectPlainBody(Project project)
        {
            return string.Empty;
        }

        private string GenerateProjectRtfBody(Project project)
        {
            return string.Empty;
        }

        private string GenerateProjectSubject(Project project)
        {
            return string.Format("Project: {0}", project.Name);
        }

        private string GenerateWorkItemHtmlBody(WorkItem item)
        {
            return this.CreateBody(item, TextFormatType.Html);
        }

        private string GenerateWorkItemPlainBody(WorkItem item)
        {
            return this.CreateBody(item, TextFormatType.PlainText);
        }

        private string GenerateWorkItemRtfBody(WorkItem item)
        {
            return this.CreateBody(item, TextFormatType.Rtf);
        }

        private string GenerateWorkItemSubject(WorkItem item)
        {
            return string.Format(@"Project:{0}\{1}:{2}", item.Project.Name, item.Type.Name, item.Title);
        }

        private AllowedValuesCollection GetAllowedAssignedTo(WIObject item)
        {
            Explorer explorer = m_App.ActiveExplorer();
            if (explorer == null)
            {
                return null;
            }
            return this.GetWorkItemByOlItem(explorer.Selection[1] as PostItem).Fields[CoreField.AssignedTo].AllowedValues;
        }

        private AllowedValuesCollection GetAllowedAssignedTo(WorkItem wi)
        {
            if (wi != null)
                return wi.Fields[CoreField.AssignedTo].AllowedValues;
            return null;
        }

        private bool CurrentTfsServer(IServerProvider ServerProvider)
        {
            String CurrentFolderPath = ActiveExplorer.CurrentFolder.FolderPath;
            return CurrentFolderPath.Replace("%2F", "/").Contains(ServerProvider.ServerName);
        }

        private List<string> GetAllowedStates(WorkItem wiItem)
        {
            var AllowedStatesList = new List<string>();
            var tmpCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                var GroupNamesList = GetGroupNamesList();

                XmlNodeList Transitions = wiItem.Type.Export(true).SelectSingleNode("descendant::TRANSITIONS").SelectNodes("TRANSITION");
                if (Transitions != null)
                    foreach (XmlNode Transition in Transitions)
                    {
                        bool equalsCurrentState = (Transition.Attributes.GetNamedItem("from").Value == wiItem.State);
                        if (!equalsCurrentState)
                            continue;

                        bool forIsNull = (Transition.Attributes.GetNamedItem("for") == null);
                        bool notIsNull = (Transition.Attributes.GetNamedItem("not") == null);

                        if (notIsNull && forIsNull)
                        {
                            // here we add one more allowed state
                            AllowedStatesList.Add(Transition.Attributes.GetNamedItem("to").Value);
                        }
                        else
                        {
                            bool isAllowed = false;
                            bool isProhibited = false;
                            bool AlreadyContains = true;

                            AlreadyContains = AllowedStatesList.Contains(Transition.Attributes.GetNamedItem("to").Value);
                            if (AlreadyContains)
                                continue;
                            if (!forIsNull)
                                isAllowed = GroupNamesList.Contains(Transition.Attributes.GetNamedItem("for").Value.Replace(@"[project]\", String.Empty));
                            if (!notIsNull)
                                isProhibited = GroupNamesList.Contains(Transition.Attributes.GetNamedItem("not").Value.Replace(@"[project]\", String.Empty));
                            // here we add one more allowed state
                            if (!isProhibited && isAllowed)
                                AllowedStatesList.Add(Transition.Attributes.GetNamedItem("to").Value);
                        }
                    }
            }
            catch (Exception exception)
            {
                Debug.WriteLine("Error in GetAllowedStates " + exception.ToString());
            }
            finally
            {
                Cursor.Current = tmpCursor;
            }
            return AllowedStatesList;
        }

        private List<string> GetGroupNamesList()
        {
            var TfsServer = m_servers.Find(CurrentTfsServer).Server;
            var gss = (IGroupSecurityService)TfsServer.GetService(typeof(IGroupSecurityService));

            string CurrentUserSid = TfsServer.AuthenticatedUserIdentity.Sid;
            var CurrentUserSidIdentity = gss.ReadIdentity(SearchFactor.Sid, CurrentUserSid, QueryMembership.Expanded);
            var GroupsNamesList = new List<string>();

            foreach (string GroupSid in CurrentUserSidIdentity.MemberOf)
            {
                GroupsNamesList.Add(gss.ReadIdentity(SearchFactor.Sid, GroupSid, QueryMembership.Expanded).DisplayName);
            }
            return GroupsNamesList;
        }

        private string GetFolderWebViewURL(WebViewType type)
        {
            if (this.m_webViewsMAP == null)
            {
                this.m_webViewsMAP = new Dictionary<WebViewType, string>();
                this.m_syncWebViewsMAP = new object();
            }
            lock (this.m_syncWebViewsMAP)
            {
                string path = null;
                bool flag = this.m_webViewsMAP.ContainsKey(type);
                if (flag)
                {
                    path = this.m_webViewsMAP[type];
                    if (File.Exists(path))
                    {
                        return path;
                    }
                }
                string htmlContent = null;
                switch (type)
                {
                    case WebViewType.WorkItemRoot:
                        htmlContent = Resources.WorkItemRootWebView;
                        break;

                    case WebViewType.TeamQueryRoot:
                        htmlContent = Resources.TeamQueryWebView;
                        break;

                    case WebViewType.MyQueryRoot:
                        htmlContent = Resources.MyQueryrWebView;
                        break;

                    default:
                        throw new NotImplementedException();
                }
                path = OutlookGlobal.CreateFolderWebViewURL(htmlContent);
                if (flag)
                {
                    this.m_webViewsMAP[type] = path;
                }
                else
                {
                    this.m_webViewsMAP.Add(type, path);
                }
                return path;
            }
        }

        private string GetProjectUri(PostItem item)
        {
            return this.GetPropertyValue(item, OlWorkItemProperties.ProjectUri.ToString());
        }

        private ItemProperty GetProperty(PostItem olItem, string name)
        {
            return olItem.ItemProperties[name];
        }

        private string GetPropertyValue(PostItem olItem, string name)
        {
            if (olItem == null)
            {
                return null;
            }
            ItemProperty property = this.GetProperty(olItem, name);
            return ((property == null) ? null : ((string)((property.Value == null) ? null : property.Value.ToString())));
        }

        private void GetRecursiveChildFolderIDs(MAPIFolder target, ref IList<string> entries)
        {
            if (target == null)
            {
                throw new ArgumentException();
            }
            foreach (MAPIFolder folder in target.Folders)
            {
                entries.Add(folder.EntryID);
                this.GetRecursiveChildFolderIDs(folder, ref entries);
            }
        }

        private string GetServerUri(PostItem olItem)
        {
            return this.GetPropertyValue(olItem, OlWorkItemProperties.ServerUri.ToString());
        }

        private WorkItem GetWorkItemByOlItem(PostItem olItem)
        {
            if (olItem == null)
            {
                return null;
            }
            string workItemUri = this.GetWorkItemUri(olItem);
            WorkItemStore store = WIObjectsStore.GetServer(this.GetServerUri(olItem)).GetStore();
            WorkItem workItem = null;
            try
            {
                workItem = store.GetWorkItem(new Uri(workItemUri));
            }
            catch
            {
            }
            return workItem;
        }

        private string GetWorkItemUri(PostItem item)
        {
            return this.GetPropertyValue(item, OlWorkItemProperties.WorkItemUri.ToString());
        }

        private OutlookUIFactory uiFactory = new OutlookUIFactory();

        private System.Drawing.Image GetImageFromPicture(string pictureId)
        {
            return System.Drawing.Image.FromStream(
               this.GetType().Assembly.GetManifestResourceStream(pictureId)
            );
        }

        private void InitButtons(CommandBar txLookerCommandBar)
        {
            CommandBarPopup workItemPopup = uiFactory.CreateParentButton(txLookerCommandBar, "Work Item");
            RegisterUIControl(UIControlType.WorkItem, workItemPopup);

            RegisterUIControl(
                UIControlType.NewWorkItem,

                uiFactory.CreateChildButtonForPopup(workItemPopup, Resources.new_work_item, Resources.new_work_item_black, Resources.UI_NEWWORKITEM_CAPTION, OnNewWorkItem)
            );

            RegisterUIControl(
                UIControlType.EditWorkItem,

                uiFactory.CreateChildButtonForPopup(workItemPopup, Resources.edit_work_item, Resources.edit_work_item_black, Resources.UI_EDITWORKITEM_CAPTION, OnEditWorkItem)
            );

            RegisterUIControl(
                UIControlType.GoToWorkItem,

                uiFactory.CreateChildButtonForBar(txLookerCommandBar, Resources.go_to_work_item, Resources.go_to_work_item_black, Resources.UI_GO_TO_WORK_ITEM, OnGoToWorkItemButtonClick)
            );

            RegisterUIControl(
                UIControlType.NewEMail,

                uiFactory.CreateChildButtonForBar(txLookerCommandBar, Resources.new_email, Resources.new_email_black, Resources.UI_EMAIL_CAPTION, OnEMailButtonClick)
            );

            RegisterUIControl(
                UIControlType.NewMeeting,

                uiFactory.CreateChildButtonForBar(txLookerCommandBar, Resources.new_meeting, Resources.new_meeting_black, Resources.UI_MEETING_CAPTION, OnMeetingButtonClick)
            );

            RegisterUIControl(
                UIControlType.NewTask,

                uiFactory.CreateChildButtonForBar(txLookerCommandBar, Resources.new_task, Resources.new_task_black, Resources.UI_TASK_CAPTION, OnTaskButtonClick)
            );

            RegisterUIControl(
                UIControlType.Update,

                uiFactory.CreateChildButtonForBar(txLookerCommandBar, Resources.update, Resources.update_black, Resources.UI_UPDATE_CAPTION, OnUpdateButtonClick)
            );

            CommandBarPopup updateOptionsPopup = uiFactory.CreateParentButton(txLookerCommandBar, Resources.UI_OPTIONS_CAPTION);
            RegisterUIControl(UIControlType.Options, updateOptionsPopup);

            RegisterUIControl(
                UIControlType.UpdateOptions,

                uiFactory.CreateChildButtonForPopup(updateOptionsPopup, Resources.update_options, Resources.update_options_black, Resources.UI_UPDATE_OPTION, btnUpdateOption_Click)
            );
            EnabledControls(UIControlType.UpdateOptions, true);

            RegisterUIControl(
                UIControlType.ContentPattern,

                uiFactory.CreateChildButtonForPopup(updateOptionsPopup, Resources.content_pattern_editor, Resources.content_pattern_editor_black, Resources.UI_CONTENT_PATTERN_EDITOR, btnContentPatternOption_Click)
            );

            CommandBarPopup queriesPopup = uiFactory.CreateParentButton(txLookerCommandBar, Resources.UI_QUERIES_CAPTION);
            RegisterUIControl(UIControlType.Queries, queriesPopup);

            RegisterUIControl(
                UIControlType.QueryManager,

                uiFactory.CreateChildButtonForPopup(queriesPopup, Resources.query_manager, Resources.query_manager_black, Resources.UI_QUERY_MANAGER_CAPTION, OnQueryManager)
            );

            RegisterUIControl(
                UIControlType.QueryViews,

                uiFactory.CreateChildButtonForPopup(queriesPopup, Resources.queries, Resources.queries_black, Resources.UI_QUERY_VIEWS_CAPTION, OnQueryViews)
            );


            CommandBarPopup changeStatePopup = uiFactory.CreateParentButton(txLookerCommandBar, Resources.UI_CHANGE_STATE);
            RegisterUIControl(UIControlType.ChangeState, changeStatePopup);

            CreateReassigneToComboBox(txLookerCommandBar);
        }

        private void InitializeOlItem(PostItem olItem, WorkItem wiItem)
        {
            List<WorkItemFieldDefinition> list = new List<WorkItemFieldDefinition>();
            foreach (Field field in wiItem.Fields)
            {
                list.Add(field.FieldDefinition);
            }
            this.InitializeOlItem(olItem, wiItem, list);
        }

        private void InitializeOlItem(PostItem olItem, WorkItem wiItem, IEnumerable<WorkItemFieldDefinition> fields)
        {
            this.InitializeOlItem(olItem, wiItem, (IEnumerable)fields);
        }

        private void InitializeOlItem(PostItem olItem, WorkItem wiItem, IEnumerable fields)
        {
            try
            {
                foreach (WorkItemFieldDefinition definition in fields)
                {
                    object workItemFieldValue = WorkItemsGlobal.GetWorkItemFieldValue(wiItem, definition.Name);
                    this.SetProperty(olItem, string.Format("@{0}", definition.Name), definition.OlFieldType, wiItem, workItemFieldValue);
                }
                this.SetServerUri(olItem, wiItem);
                this.SetProjectUri(olItem, wiItem);
                this.SetWorkItemUri(olItem, wiItem);
                olItem.UnRead = false;
                olItem.Save();
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in InitializeOlItem method: " + exception.ToString());
            }
        }

        private void LoadConfigs(ref WorkItemAppConfigs configs)
        {
            if (configs == null)
            {
                configs = new WorkItemAppConfigs();
            }
            configs.AutomaticUpdate = Settings.Default.AutomaticUpdate;
            configs.AutomaticUpdatePeriod = Settings.Default.AutomaticUpdatePeriod;
            this.ApplicationConfigsChanged += new EventHandler(this.OnApplicationConfigsChanged);
        }

        private void LoadStateButtons(List<string> allowedStates, CommandBarPopup parent)
        {
            try
            {
                foreach (string str in allowedStates)
                {
                    StateButton item = new StateButton(this, parent, str, string.Format(Resources.STRING_CHANGE_STATE_TO, str));
                    item.Visible = true;
                    item.Style = MsoButtonStyle.msoButtonCaption;
                    lock (this)
                    {
                        bool flag = true;
                        foreach (StateButton button2 in this.m_stateChangeButtons)
                        {
                            if (item.Name == button2.Name)
                            {
                                flag = false;
                                break;
                            }
                        }
                        if (flag)
                        {
                            this.m_stateChangeButtons.Add(item);
                        }
                    }
                }
                this.EnabledControls(UIControlType.ChangeState, true);
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog("Error in LoadStateButtons " + exception.ToString());
                foreach (StateButton button in this.m_stateChangeButtons)
                {
                    button.RemoveButton();
                }
                this.m_stateChangeButtons.Clear();
                CommandBarPopup popup = null;
                foreach (CommandBarControl control in this.m_UIControls[UIControlType.ChangeState])
                {
                    popup = control as CommandBarPopup;
                }
                if (popup != null)
                {
                    int count = popup.Controls.Count;
                    for (int i = 1; i < count; i++)
                    {
                        popup.Controls[i].Delete(true);
                    }
                    this.LoadStateButtons(allowedStates, popup);
                }
            }
        }

        private void LoadWIProjectSetting(Uri serverUri)
        {
            if (File.Exists(WorkItemExtentionGlobal.GetContentPatterFile(this.m_DataProvider.AppStoreFolderPath, serverUri)))
            {
                try
                {
                    using (FileStream stream = new FileStream(WorkItemExtentionGlobal.GetContentPatterFile(this.m_DataProvider.AppStoreFolderPath, serverUri), FileMode.Open))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        IEnumerable<WIProjectSettings> settings = (IEnumerable<WIProjectSettings>)formatter.Deserialize(stream);
                        WIAppGlobal.Configs.SetProjectSettings(settings);
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog("Error in LoadWIProjectSetting " + exception.ToString());
                }
            }
        }

        private Dictionary<BackgroundMultiWorker, WIStoredQuery> ActiveWorkers = new Dictionary<BackgroundMultiWorker, WIStoredQuery>();



        private void NotActivationMessage()
        {
            MessageBox.Show("Looker is in trial mode", Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        public void OlWorkItemChange(WorkItem wiItem)
        {
            new WorkItemForm(wiItem, this).ShowDialog();
        }

        public void OlWorkItemUpdate(WorkItem wiItem, object olObject)
        {
            if (!object.ReferenceEquals(olObject, null))
            {
                PostItem olItem = (PostItem)olObject;
                this.InitializeOlItem(olItem, wiItem);
            }
        }

        private void OnApplicationConfigsChanged(object sender, EventArgs args)
        {
            try
            {
                Explorer activeExplorer = this.ActiveExplorer;
                WIObject objectByFolder = WIObject.GetObjectByFolder(activeExplorer.CurrentFolder);
                if (objectByFolder != null)
                {
                    activeExplorer.SelectFolder(objectByFolder.Folder);
                    this.UpdateStateControls(this.ApplicationConfigs);
                    if (this.m_updateTimer != null)
                    {
                        this.m_updateTimer.Dispose();
                    }
                    if (this.m_configs.AutomaticUpdate)
                    {
                        this.m_updateTimer = new Timer(new TimerCallback(this.UpdateTimerCallBack), null, 0, this.m_configs.AutomaticUpdatePeriod * 0x3e8);
                    }
                }
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnApplicationConfigsChanged method: " + exception.ToString());
            }
        }

        private void OnBeforeFolderSwitch(object NewFolder, ref bool Cancel)
        {
            try
            {
                MAPIFolder folder = NewFolder as MAPIFolder;
                bool bEnabled = this.CheckFolder(folder);
                this.EnabledControls(bEnabled);
                this.EnabledControls(UIControlType.ReassignTo, false);
                if (!bEnabled)
                {
                    if (this.m_updateTimer != null)
                    {
                        this.m_updateTimer.Dispose();
                    }
                }
                else
                {
                    this.UpdateStateControls(this.ApplicationConfigs);
                    this.UpdateStateControls(folder);
                    if (this.m_configs.AutomaticUpdate)
                    {
                        if (this.m_updateTimer != null)
                        {
                            this.m_updateTimer.Dispose();
                        }
                        this.m_updateTimer = new Timer(new TimerCallback(this.UpdateTimerCallBack), null, 0, this.m_configs.AutomaticUpdatePeriod * 0x3e8);
                    }
                    else
                    {
                        this.AsyncUpdateData(folder);
                    }
                }
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnBeforeFolderSwitch method: " + exception.ToString());
            }
        }

        public void OnCreateWorkItemClick(IRibbonControl control)
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                new CreateWorkItemFromOlItemForm(m_App.ActiveInspector().CurrentItem, this).ShowDialog();
            }
        }

        private bool OnEditWorkItem()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                try
                {
                    Explorer activeExplorer = this.ActiveExplorer;
                    WIObject objectByFolder = WIObject.GetObjectByFolder(activeExplorer.CurrentFolder);
                    if (((objectByFolder != null) && (objectByFolder.Type == WIObjectType.Query)) && (activeExplorer.Selection.Count != 0))
                    {
                        this.EditWorkItem(activeExplorer.Selection[1] as PostItem);
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnEditWorkItem method: " + exception.ToString());
                }
            }

            return false;
        }

        private bool OnEMailButtonClick()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                try
                {
                    Explorer explorer = m_App.ActiveExplorer();
                    if (!object.ReferenceEquals(explorer.CurrentFolder, null))
                    {
                        this.CreateOlInspectorByFolder(explorer.CurrentFolder, OlItemType.olMailItem);
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnEMailButtonClick method: " + exception.ToString());
                }
            }

            return false;
        }

        private void OnFolderContextMenu(CommandBar CommandBar, MAPIFolder Folder)
        {
            if (WIObject.GetObjectByFolder(Folder) != null)
            {
                foreach (CommandBarControl control in CommandBar.Controls)
                {
                    if (((((control.Id == 0x9c4) || (control.Id == 0x9ca)) || ((control.Id == 0x9d0) || (control.Id == 0x67c))) || (((control.Id == 0x1ed0) || (control.Id == 0x2730)) || (control.Id == 750))) || (control.Id == 0x9c3))
                    {
                        //control.Enabled = false;
                    }
                }
            }
        }

        private bool OnGoToWorkItemButtonClick()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                new GoToWorkItemForm(this).ShowDialog();
            }

            return false;
        }

        private bool OnMeetingButtonClick()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                try
                {
                    Explorer explorer = m_App.ActiveExplorer();
                    if (!object.ReferenceEquals(explorer.CurrentFolder, null))
                    {
                        this.CreateOlInspectorByFolder(explorer.CurrentFolder, OlItemType.olAppointmentItem);
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnMeetingButtonClick method: " + exception.ToString());
                }
            }

            return false;
        }

        private void OnNewInspector(Inspector inspector)
        {
            try
            {
                Explorer activeExplorer = this.ActiveExplorer;
                WIObject objectByFolder = WIObject.GetObjectByFolder(activeExplorer.CurrentFolder);
                if (objectByFolder != null)
                {
                    switch (objectByFolder.Type)
                    {
                        case WIObjectType.Server:
                        case WIObjectType.Project:
                        case WIObjectType.QueriesRoot:
                        case WIObjectType.QueriesGroup:
                            return;

                        case WIObjectType.Query:
                            break;

                        default:
                            throw new NotImplementedException();
                    }
                    if (!this.m_bStandartInspector && (activeExplorer.Selection.Count != 0))
                    {
                        PostItem olItem = activeExplorer.Selection[1] as PostItem;
                        if (olItem != null)
                        {
                            this.m_item = olItem;
                            WorkItem workItemByOlItem = this.GetWorkItemByOlItem(olItem);
                            string str = inspector.CurrentItem.GetType().InvokeMember("EntryID", BindingFlags.GetProperty, null, inspector.CurrentItem, null) as string;
                            if (str == olItem.EntryID)
                            {
                                m_item.Open += delegate(ref bool bCancel)
                                {
                                    bCancel = true;
                                };
                                EditWorkItem(olItem);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnNewInspector method: " + exception.ToString());
            }
        }

        private void OnNewServers(object sender, IEnumerable<IServerProvider> servers)
        {
            List<WIServerProvider> list = new List<WIServerProvider>();
            foreach (IServerProvider provider in servers)
            {
                WIServerProvider item = new WIServerProvider(provider);
                list.Add(item);
                this.LoadWIProjectSetting(provider.ServerUri);
                this.m_servers.Add(provider);
            }
            WIObjectsStore.AddServers(list);
        }

        private bool OnNewWorkItem()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                try
                {
                    WIProjectProvider current = null;
                    WIObject objectByFolder = WIObject.GetObjectByFolder(this.ActiveExplorer.CurrentFolder);
                    if (objectByFolder != null)
                    {
                        switch (objectByFolder.Type)
                        {
                            case WIObjectType.Project:
                                current = objectByFolder as WIProjectProvider;
                                break;

                            case WIObjectType.QueriesRoot:
                                current = (objectByFolder as WIQueriesRoot).ProjectProvider;
                                break;

                            case WIObjectType.QueriesGroup:
                                current = (objectByFolder as WIQueriesGroup).ProjectProvider;
                                break;

                            case WIObjectType.Query:
                                current = (objectByFolder as WIStoredQuery).ProjectProvider;
                                break;
                        }
                    }
                    WorkItemTypeSelectionForm form = new WorkItemTypeSelectionForm(WIObjectsStore.Servers, current);
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        if (form.WorkItemType == null)
                        {
                            MessageBox.Show(Resources.WORKITEM_CREATE_ERROR_MESSAGE, Resources.EXTENTION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        }
                        else
                        {
                            WorkItem wiItem = null;
                            try
                            {
                                wiItem = form.WorkItemType.NewWorkItem();
                            }
                            catch
                            {
                            }
                            if (wiItem == null)
                            {
                                MessageBox.Show(Resources.WORKITEM_CREATE_ERROR_MESSAGE, Resources.EXTENTION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            }
                            else
                            {
                                this.AddWorkItem(wiItem);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnNewWorkItem method: " + exception.ToString());
                }
            }

            return false;
        }

        private void OnPreRemoveServers(object sender, IEnumerable<IServerProvider> servers)
        {
            List<Uri> uries = new List<Uri>();
            foreach (IServerProvider provider in servers)
            {
                uries.Add(provider.ServerUri);
            }
            WIObjectsStore.RemoveServers(uries);
        }

        private bool OnQueryManager()
        {
            try
            {
                if (this.m_DataProvider.LicenceType != LicenceType.Full)
                {
                    this.NotActivationMessage();
                }
                else
                {
                    new WIQLManagerForm(this).Show();
                }
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog("Error in OnQueryManager " + exception.ToString());
            }

            return false;
        }

        private bool OnQueryViews()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                var queryViewsForm = new WIQLViewForm();
                queryViewsForm.ChangesApplied += ActiveExplorer_FolderSwitch;
                queryViewsForm.ShowDialog();
            }

            return false;
        }

        private bool OnReassignToChange(string selectedItemText)
        {
            try
            {
                Explorer activeExplorer = this.ActiveExplorer;
                WIObject objectByFolder = WIObject.GetObjectByFolder(activeExplorer.CurrentFolder);
                if ((objectByFolder != null) && (objectByFolder.Type == WIObjectType.Query))
                {
                    var wi = GetSelectedWorkItem();
                    if ((wi == null) || (selectedItemText == Resources.STRING_REASSIGN_TO_DESCRIPTION))
                    {
                        return false;
                    }
                    wi.Fields[CoreField.AssignedTo].Value = selectedItemText;
                    try
                    {
                        wi.Save();
                        ActiveExplorer_FolderSwitch();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnEditWorkItem method: " + ex);
            }

            return false;
        }

        private bool OnTaskButtonClick()
        {
            if (this.m_DataProvider.LicenceType != LicenceType.Full)
            {
                this.NotActivationMessage();
            }
            else
            {
                try
                {
                    Explorer explorer = m_App.ActiveExplorer();
                    if (!object.ReferenceEquals(explorer.CurrentFolder, null))
                    {
                        this.CreateOlInspectorByFolder(explorer.CurrentFolder, OlItemType.olTaskItem);
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog(this.Name + ". Error in OnMeetingButtonClick method: " + exception.ToString());
                }
            }

            return false;
        }

        private bool OnUpdateButtonClick()
        {
            var tmpCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                ActiveExplorer_FolderSwitch();
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog("Error ocured while updating" + ex);
            }
            finally
            {
                Cursor.Current = tmpCursor;
            }


            MAPIFolder currentFolder = m_App.ActiveExplorer().CurrentFolder;
            this.AsyncUpdateData(currentFolder);

            return false;
        }

        private void RaiseApplicationConfigsChanged()
        {
            CommonGlobal.RaiseEventHandler(this.m_ApplicationConfigsChangedEH, new object[] { this, EventArgs.Empty }, this.m_syncApplicationConfigs);
        }

        private void RegisterExplorer(Explorer explorer)
        {
            explorer.BeforeFolderSwitch += OnBeforeFolderSwitch;
            this.m_explorers.Add(explorer);
        }

        private void RegisterUIControl(UIControlType ctrlType, CommandBarControl ctrl)
        {
            try
            {
                List<CommandBarControl> list = null;
                if (!this.m_UIControls.ContainsKey(ctrlType))
                {
                    list = new List<CommandBarControl>();
                    this.m_UIControls[ctrlType] = list;
                }
                else
                {
                    list = this.m_UIControls[ctrlType];
                }
                list.Add(ctrl);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(this.Name + ". Error in RegisterUIControl method: " + exception.ToString());
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in RegisterUIControl method: " + exception.ToString());
            }
        }

        private void SaveConfigs(WorkItemAppConfigs configs)
        {
            Settings.Default.AutomaticUpdate = configs.AutomaticUpdate;
            Settings.Default.AutomaticUpdatePeriod = configs.AutomaticUpdatePeriod;
            Settings.Default.Save();
        }

        private void SaveWIProjectSettings(IEnumerable<WIProjectSettings> projectSettings, Uri serverUri)
        {
            string contentPatterFile = WorkItemExtentionGlobal.GetContentPatterFile(this.m_DataProvider.AppStoreFolderPath, serverUri);
            List<WIProjectSettings> graph = (List<WIProjectSettings>)projectSettings;
            using (FileStream stream = new FileStream(contentPatterFile, FileMode.OpenOrCreate, FileAccess.Write))
            {
                try
                {
                    new BinaryFormatter().Serialize(stream, graph);
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog("Error in SaveWIProjectSettings " + exception.ToString());
                }
            }
        }

        private void SetProjectUri(PostItem olItem, WorkItem wiItem)
        {
            this.SetProperty(olItem, OlWorkItemProperties.ProjectUri.ToString(), OlUserPropertyType.olText, wiItem.Project.Uri.ToString());
        }

        private void SetProperty(PostItem olItem, string propertyname, OlUserPropertyType type, object value)
        {
            ItemProperty property = this.GetProperty(olItem, propertyname);
            if (property == null)
            {
                property = olItem.ItemProperties.Add(propertyname, type, false, Missing.Value);
            }
            property.Value = value;
        }

        private void SetProperty(PostItem olItem, string propertyname, OlUserPropertyType type, WorkItem workItem, object value)
        {
            ItemProperty property = this.GetProperty(olItem, propertyname);
            if (property == null)
            {
                property = olItem.ItemProperties.Add(propertyname, type, false, Missing.Value);
            }
            property.Value = value;
        }

        private void SetServerUri(PostItem olItem, WorkItem wiItem)
        {
            this.SetProperty(olItem, OlWorkItemProperties.ServerUri.ToString(), OlUserPropertyType.olText, wiItem.Store.TeamFoundationServer.Uri.ToString());
        }

        private void SetWorkItemUri(PostItem olItem, WorkItem wiItem)
        {
            this.SetProperty(olItem, OlWorkItemProperties.WorkItemUri.ToString(), OlUserPropertyType.olText, wiItem.Uri.ToString());
        }

        public void ShutDown()
        {
            if (Directory.Exists(WorkItemExtentionGlobal.LookerTempFolder))
            {
                Directory.Delete(WorkItemExtentionGlobal.LookerTempFolder, true);
            }
            this.SaveConfigs(WIAppGlobal.Configs);
        }

        public EventSink EventSink
        {
            get { return eventSink; }
            set { eventSink = value; }
        }

        private Application GetOutlookApplicationObject()
        {
            return m_DataProvider.Application;
        }

        public void StartUp(IExtentionDataProvider dataProvider)
        {
            try
            {
                if (eventSink != null)
                {
                    // subscribing to the events from Ribbon control
                    eventSink.Subscribe(EventNames.CreateWorkItem, delegate() { OnCreateWorkItemClick(null); });
                }

                LogManager.WriteMessageToCustomLog(this.Name + ": startup begin");
                m_DataProvider = dataProvider;

                //m_App = this.m_DataProvider.Application;
                m_App = GetOutlookApplicationObject();
                // m_App.
                this.LoadConfigs(ref this.m_configs);
                this.CreateAppUIControls();
                this.m_DataProvider.NewServers += OnNewServers;
                this.m_DataProvider.PreRemoveServers += OnPreRemoveServers;
                this.m_inspectors = m_App.Inspectors;
                this.m_inspectors.NewInspector += OnNewInspector;
                Explorer explorer = m_App.ActiveExplorer();
                this.RegisterExplorer(explorer);
                m_App.Explorers.NewExplorer += RegisterExplorer;
                WorkItemExtentionGlobal.ExtentionDataProvider.Session = this.m_DataProvider.Session;
                //this.ActiveExplorer.SelectionChange += ActiveExplorer_SelectionChange;
                ActiveExplorer.FolderSwitch += ActiveExplorer_FolderSwitch;
                this.EnabledControls(UIControlType.ContentPattern, true);
                this.EnabledControls(UIControlType.UpdateOptions, true);
                this.EnabledControls(UIControlType.GoToWorkItem, true);
                m_App.FolderContextMenuDisplay += OnFolderContextMenu;
                outlookWindow = FindOutlookWindow();
                siblingWindow = SafeNativeMethods.FindWindowEx(outlookWindow, IntPtr.Zero, SIBLING_WINDOW_CLASS, null);
                LogManager.WriteMessageToCustomLog(this.Name + " loaded");
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error:" + exception);
            }
        }

        private void ActiveExplorer_FolderSwitch()
        {
            Explorer explorer = m_App.ActiveExplorer();
            WIObject objectByFolder = WIObject.GetObjectByFolder(explorer.CurrentFolder);
            if (objectByFolder != null)
            {
                switch (objectByFolder.Type)
                {
                    case WIObjectType.Query:
                        if (panelManager != null)
                        {
                            panelManager.HideBarControl();
                            panelManager = null;
                        }

                        olQueryViewControl = CreateOLQueryViewControl(objectByFolder);
                        olQueryViewControl.QueryResultGrid.CellDoubleClick += OnQueryResultGrid_CellDoubleClick;
                        olQueryViewControl.QueryResultGrid.SelectionChanged += OnQueryResultGrid_SelectionChanged;
                        olQueryViewControl.QueryResultGrid.KeyDown += OnQueryResultGrid_KeyDown;
                        panelManager = CreatePanelManager();
                        panelManager.ShowBarControl(olQueryViewControl);

                        break;

                    case WIObjectType.Server:
                        if (panelManager != null)
                        {
                            panelManager.HideBarControl();
                            panelManager = null;
                        }
                        
                        panelManager = CreatePanelManager();
                        OLServerViewControl = CreateOLServerViewControl(objectByFolder);
                        OLServerViewControl.lnkProjects.LinkClicked += lnkProjects_LinkClicked;
                        panelManager.ShowBarControl(OLServerViewControl);
                        break;
                    default:
                        if (panelManager != null)
                        {
                            panelManager.HideBarControl();
                            panelManager = null;
                        }
                        break;
                }
            }
            else
            {
                if (panelManager != null)
                {
                    panelManager.HideBarControl();
                    panelManager = null;
                }
            }
        }

        private void OnQueryResultGrid_SelectionChanged(object sender, EventArgs e)
        {
            if (refreshTimer != null)
                refreshTimer.Stop();
            refreshTimer = new System.Windows.Forms.Timer { Interval = 600 };
            refreshTimer.Tick += OnRefresTimerTick;
            refreshTimer.Start();
        }

        private void OnQueryResultGrid_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    e.Handled = true;
                    OpentWorkItemForm();
                    break;
                default:
                    break;

            }
        }

        private void OnRefresTimerTick(object sender, EventArgs e)
        {
            refreshTimer.Stop();
            refreshTimer = null;
            RefresStateButtons();
        }

        private void RefresStateButtons()
        {
            foreach (var button in m_stateChangeButtons)
            {
                button.RemoveButton();
            }
            m_stateChangeButtons.Clear();
            CommandBarPopup popup = null;
            foreach (var control in m_UIControls[UIControlType.ChangeState])
            {
                popup = control as CommandBarPopup;
            }
            if (popup != null)
            {
                try
                {
                    var controlCount = popup.Controls.Count;
                    for (var i = 1; i < controlCount; i++)
                    {
                        popup.Controls[i].Delete(true);
                    }
                }
                catch (NullReferenceException ex)
                {
                    LogManager.WriteMessageToCustomLog(ex);
                }

                try
                {
                    var wi = GetSelectedWorkItem();

                    if (wi != null)
                    {
                        InitReassignCombo(wi);
                        var allowedStates = GetAllowedStates(wi);

                        if (allowedStates.Count != 0)
                        {
                            var popupItems = m_UIControls[UIControlType.ChangeState];
                            if (popupItems.Count == 1)
                            {
                                var parent = (CommandBarPopup)popupItems[0];

                                if (parent != null)
                                {
                                    parent.Enabled = true;
                                    LoadStateButtons(allowedStates, parent);
                                }
                            }
                        }
                        else
                        {
                            var popupItems = m_UIControls[UIControlType.ChangeState];
                            if (popupItems.Count == 1)
                            {
                                var parent = (CommandBarPopup)popupItems[0];
                                if (parent != null)
                                {
                                    parent.Enabled = false;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteMessageToCustomLog(ex);
                }
            }

        }

        private void InitReassignCombo(WorkItem wi)
        {
            try
            {
                var explorer = m_App.ActiveExplorer();
                var objectByFolder = WIObject.GetObjectByFolder(explorer.CurrentFolder);
                if ((objectByFolder != null) && (objectByFolder.Type == WIObjectType.Query))
                {
                    CommandBarComboBox item = null;
                    foreach (var control in m_UIControls[UIControlType.ReassignTo])
                    {
                        item = control as CommandBarComboBox;
                    }
                    if ((item != null) && (wi != null))
                    {
                        m_UIControls[UIControlType.ReassignTo].Remove(item);
                        item.Delete(false);
                        CreateReassigneToComboBox(TeamXpandCommandBar);
                        foreach (var control in m_UIControls[UIControlType.ReassignTo])
                        {
                            item = control as CommandBarComboBox;
                        }
                        if (item != null)
                        {
                            var allowedAssignedTo = GetAllowedAssignedTo(wi);
                            var list = new List<string>();
                            foreach (string str in allowedAssignedTo)
                            {
                                if (!list.Contains(str))
                                {
                                    list.Add(str);
                                }
                            }
                            m_comboReassignToItemsCount = list.Count + 1;
                            for (var i = 0; i < list.Count; i++)
                            {
                                item.AddItem(allowedAssignedTo[i], i + 1);
                            }
                            EnabledControls(UIControlType.ReassignTo, true);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine("Error in filling comboReassignTo " + exception.ToString());
                LogManager.WriteMessageToCustomLog("Error in filling comboReassignTo " + exception.ToString());
            }
        }

        private WorkItem GetSelectedWorkItem()
        {
            try
            {
                if (olQueryViewControl != null)
                {

                    var selectedIds = olQueryViewControl.QueryResultGrid.GetSelectedIds();
                    if (selectedIds.Length == 1)
                    {
                        var wiStore = olQueryViewControl.QueryResultGrid.WorkItemCollection.Store;
                        return wiStore.GetWorkItem(selectedIds[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog(ex);
            }
            return null;
        }

        private static void lnkProjects_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var explorer = m_App.ActiveExplorer();
            var OutlookNamespace = m_App.GetNamespace("MAPI");
            try
            {
                explorer.CurrentFolder = OutlookNamespace.GetFolderFromID(e.Link.LinkData.ToString(), explorer.CurrentFolder.StoreID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void OnQueryResultGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
                OpentWorkItemForm();
        }

        private void OpentWorkItemForm()
        {
            var tmpCursor = Cursor.Current;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                var wi = GetSelectedWorkItem();

                if (wi != null)
                {
                    var workItemForm = new WorkItemForm(wi, this);
                    workItemForm.ChangesApplied += ActiveExplorer_FolderSwitch;
                    workItemForm.Show();
                }
                Cursor.Current = tmpCursor;
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog(ex);
            }
            finally
            {
                Cursor.Current = tmpCursor;
            }
        }

        private OLQueryViewControl CreateOLQueryViewControl(WIObject objectByFolder)
        {
            WorkItemStore store = objectByFolder.GetStore();
            var wiStoredQuery = objectByFolder as WIStoredQuery;
            StoredQuery storedQuery = null;
            if (wiStoredQuery != null)
                storedQuery = wiStoredQuery.GetQuery();

            return storedQuery != null ? new OLQueryViewControl(store, storedQuery) : null;
        }

        private OLServerViewControl CreateOLServerViewControl(WIObject objectByFolder)
        {
            List<WIObject> Projects = new List<WIObject>();

            foreach (WIObject child in objectByFolder.ChildItems)
            {
                if (!Projects.Contains(child))
                    Projects.Add(child);
            }

            Uri curServerUri = null;
            foreach (var server in m_servers)
            {
                if (objectByFolder.FolderName.Contains(server.ServerName))
                {
                    curServerUri = server.Server.Uri;
                }
            }

            return new OLServerViewControl(curServerUri, Projects);
        }

        private static IntPtr FindOutlookWindow()
        {
            System.Diagnostics.Process[] processes = Process.GetProcessesByName(OUTLOOK_PROCESS_NAME);

            if (processes == null || processes.Length == 0)
                return IntPtr.Zero;

            return processes[0].MainWindowHandle;
        }

        private PanelManager CreatePanelManager()
        {
            Thread.Sleep(1000);
            //IntPtr outlookWindow = FindOutlookWindow();

            if (outlookWindow == IntPtr.Zero)
                return null;
           // IntPtr siblingWindow = SafeNativeMethods.FindWindowEx(outlookWindow, IntPtr.Zero, SIBLING_WINDOW_CLASS, null);
            if (siblingWindow == IntPtr.Zero)
                return null;

            return new PanelManager(outlookWindow, siblingWindow);
        }

        #region Update methods
        private void UpdateData(MAPIFolder folder)
        {
            List<string> list;
            try
            {
                try
                {
                    WIObject objectByFolder = WIObject.GetObjectByFolder(folder);
                    bool bView = true;
                    if (folder.Items.Count == 0)
                    {
                        bView = false;
                    }
                    if (objectByFolder != null)
                    {
                        lock ((list = this.m_loadedFolders))
                        {
                            if (this.m_loadedFolders.Contains(folder.EntryID))
                            {
                                return;
                            }
                            this.m_loadedFolders.Add(folder.EntryID);
                        }
                        switch (objectByFolder.Type)
                        {
                            case WIObjectType.Server:
                            case WIObjectType.Project:
                            case WIObjectType.QueriesRoot:
                            case WIObjectType.QueriesGroup:
                                this.EnabledControls(UIControlType.ChangeState, false);
                                objectByFolder.Update();
                                return;

                            case WIObjectType.Query:
                                //ActiveExplorer_FolderSwitch();
                                return;
                        }
                        throw new NotImplementedException();
                    }
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog(this.Name + ". Error in UpdateData method: " + exception.ToString());
                }
            }
            finally
            {
                lock ((list = this.m_loadedFolders))
                {
                    this.m_loadedFolders.Remove(folder.EntryID);
                }
            }
        }

        private void UpdateMainMenuBar()
        {
            try
            {
                CommandBarPopup extentionMenuItem = uiFactory.CreateParentForPupup(this.m_DataProvider.AppMenuItemRoot,
                                                                       Resources.UI_EXTENTION_MENUITEM_CAPTION);

                RegisterUIControl(
                    UIControlType.GoToWorkItem,

                    uiFactory.CreateChildButtonForPopup(extentionMenuItem, Resources.go_to_work_item, Resources.go_to_work_item_black, Resources.UI_GO_TO_WORK_ITEM, OnGoToWorkItemButtonClick)
                );
                RegisterUIControl(
                    UIControlType.NewWorkItem,

                    uiFactory.CreateChildButtonForPopup(extentionMenuItem, Resources.new_work_item, Resources.new_work_item_black, Resources.UI_NEWWORKITEM_CAPTION, OnNewWorkItem)
                );
                RegisterUIControl(
                    UIControlType.EditWorkItem,

                    uiFactory.CreateChildButtonForPopup(extentionMenuItem, Resources.edit_work_item, Resources.edit_work_item_black, Resources.UI_EDITWORKITEM_CAPTION, OnEditWorkItem)
                );
                RegisterUIControl(
                    UIControlType.NewEMail,

                    uiFactory.CreateChildButtonForPopup(extentionMenuItem, Resources.new_email, Resources.new_email_black, Resources.UI_EMAIL_CAPTION, OnEMailButtonClick)
                );
                RegisterUIControl(
                    UIControlType.NewMeeting,

                    uiFactory.CreateChildButtonForPopup(extentionMenuItem, Resources.new_meeting, Resources.new_meeting_black, Resources.UI_MEETING_CAPTION, OnMeetingButtonClick)
                );
                RegisterUIControl(
                    UIControlType.NewTask,

                    uiFactory.CreateChildButtonForPopup(extentionMenuItem, Resources.new_task, Resources.new_task_black, Resources.UI_TASK_CAPTION, OnTaskButtonClick)
                );

                CommandBarPopup updateOptionsMenuItem = uiFactory.CreateParentForPupup(extentionMenuItem, Resources.UI_OPTIONS_CAPTION);
                RegisterUIControl(
                    UIControlType.UpdateOptions,

                    uiFactory.CreateChildButtonForPopup(updateOptionsMenuItem, Resources.update, Resources.update_black, Resources.UI_UPDATE_OPTION, btnUpdateOption_Click)
                );
                RegisterUIControl(
                    UIControlType.ContentPattern,

                    uiFactory.CreateChildButtonForPopup(updateOptionsMenuItem, Resources.content_pattern_editor, Resources.content_pattern_editor_black, Resources.UI_CONTENT_PATTERN_EDITOR, btnContentPatternOption_Click)
                );

                CommandBarPopup queriesMenuItem = uiFactory.CreateParentForPupup(extentionMenuItem, Resources.UI_QUERIES_CAPTION);
                RegisterUIControl(
                    UIControlType.QueryManager,

                    uiFactory.CreateChildButtonForPopup(queriesMenuItem, Resources.query_manager, Resources.query_manager_black, Resources.UI_QUERY_MANAGER_CAPTION, OnQueryManager)
                );
                RegisterUIControl(
                    UIControlType.QueryViews,

                    uiFactory.CreateChildButtonForPopup(queriesMenuItem, Resources.queries, Resources.queries_black, Resources.UI_QUERY_VIEWS_CAPTION, OnQueryViews)
                );
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in UpdateMainMenuBar method: " + exception.ToString());
            }
        }

        private void UpdateStateControls(MAPIFolder folder)
        {
            try
            {
                WIObject objectByFolder = WIObject.GetObjectByFolder(folder);
                if (objectByFolder != null)
                {
                    switch (objectByFolder.Type)
                    {
                        case WIObjectType.Server:
                        case WIObjectType.Project:
                        case WIObjectType.QueriesRoot:
                        case WIObjectType.QueriesGroup:
                            this.EnabledControls(UIControlType.EditWorkItem, false);
                            return;

                        case WIObjectType.Query:
                            this.EnabledControls(UIControlType.EditWorkItem, true);
                            return;
                    }
                    throw new NotImplementedException();
                }
                this.EnabledControls(false);
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog(this.Name + ". Error in UpdateStateControls method: " + exception.ToString());
            }
        }

        private void UpdateStateControls(WorkItemAppConfigs configs)
        {
            this.EnabledControls(UIControlType.Update, !configs.AutomaticUpdate);
        }

        private void UpdateTimerCallBack(object state)
        {
            try
            {
                MAPIFolder currentFolder = this.ActiveExplorer.CurrentFolder;
                if (this.CheckFolder(currentFolder))
                {
                    this.UpdateData(currentFolder);
                }
            }
            catch
            {
            }
        }  
        #endregion

        #endregion

        #region Nested Types

        private class InitializeOlItemProperties
        {
            // Fields
            private List<WorkItemFieldDefinition> _displayFields;
            private PostItem _olItem;
            private WIStoredQuery _query;
            private WorkItem _wiItem;

            // Methods
            public InitializeOlItemProperties(PostItem olItem, WorkItem wiItem, List<WorkItemFieldDefinition> displayFields, WIStoredQuery query)
            {
                this._olItem = olItem;
                this._wiItem = wiItem;
                this._displayFields = displayFields;
                this._query = query;
            }

            // Properties
            public List<WorkItemFieldDefinition> DisplayFields
            {
                get
                {
                    return this._displayFields;
                }
            }

            public PostItem OlItem
            {
                get
                {
                    return this._olItem;
                }
                set
                {
                    this._olItem = value;
                }
            }

            public WIStoredQuery Query
            {
                get
                {
                    return this._query;
                }
            }

            public WorkItem WiItem
            {
                get
                {
                    return this._wiItem;
                }
            }
        } 

        #endregion

        #region Delegates
        public delegate void MethodInvokerListCommandBarPopup(List<string> list, CommandBarPopup popup); 
        #endregion
    }
}
